package com.lich.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.lich.entity.AppError;
import com.lich.entity.Product;
import com.lich.entity.graph.ErrorAnalysis;
import com.lich.entity.vo.Page;
import com.lich.entity.vo.Result;
import com.lich.service.AppErrorService;
import com.lich.service.ProductService;
import com.lich.service.graph.ErrorAnalysisService;
import com.lich.util.ExcelUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/appError")
public class AppErrorController {

	@Resource
	AppErrorService appErrorService;
	@Resource
	ProductService productService;
	@Resource
	ErrorAnalysisService errorAnalysisService;
	private static Logger logger = LoggerFactory.getLogger(AppErrorController.class);
	/**
	 * @description 查看APP页面
	 * @date 2016年8月31日
	 * @author luosf
	 * @param pageParam
	 * @return
	 */
	@RequestMapping(value = "/list", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView getPage(Page page, AppError appError) {
		Result<Page<AppError>> result = new Result<>();
		List<AppError> appErrors = null;
		appError.setPage(page);
		// List<AppError> tree = new ArrayList<>();
		try {
			Product product = productService.selectById(Integer.parseInt(appError.getProductId()));
			appError.setProductId(product.getUuid());
			page = appErrorService.getPage(appError);
			// getTree(tree, AppErrors, 1, true, AppError.getProductId());
		} catch (IllegalAccessException | InvocationTargetException e) {
			result.setSuccess(false);
			result.setMessage("获取报错信息失败");
			logger.error("获取报错信息失败 : "+e.getMessage());
		}
		result.setObject(page);
		result.setSuccess(true);
		result.setMessage("获取报错信息成功");
		return new ModelAndView("manager/appError/list", "result", result);
	}

	/**
	 * @description 查看APP页面
	 * @date 2016年8月31日
	 * @author luosf
	 * @param pageParam
	 * @return
	 */
	@RequestMapping(value = "/report", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView report(AppError appError) {
		Result<Page<AppError>> result = new Result<>();
		result.setSuccess(true);
		result.setMessage("获取产品数据成功");
		return new ModelAndView("manager/appError/appErrorReport", "result", result);
	}

	/**
	 * @description 添加登录时间
	 * @date 2016年8月29日
	 * @author luosf
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ModelAndView add(@RequestBody AppError appError) {
		Result<AppError> result = new Result<>();
		try {
			if (appErrorService.add(appError) > 0) {
				result.setSuccess(true);
				result.setMessage("添加错误日志成功");
			} else {
				result.setSuccess(true);
				result.setMessage("添加错误日志失败 ");
			}
		} catch (Exception e) {
			result.setSuccess(true);
			result.setMessage("添加错误日志失败 ");
			logger.error("添加错误日志失败 : "+e.getMessage());
		}
		return new ModelAndView(new MappingJackson2JsonView(), "result", result);
	}

	/**
	 * @description 添加app错误信息
	 * @date 2016年8月29日
	 * @author luosf
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/postData", method = RequestMethod.POST)
	public void addList(@RequestBody List<AppError> appErrors, HttpServletResponse res) throws IOException {
		PrintWriter writer = res.getWriter();
		JSONArray arr = new JSONArray();
		JSONObject obj = new JSONObject();

		Result<AppError> result = new Result<>();
		try {
			System.out.println("接收到的报错信息-------------"+JSONArray.fromObject(appErrors));
			if (appErrorService.addList(appErrors) > 0) {
				result.setSuccess(true);
				result.setMessage("添加错误日志成功");

				obj.put("results", "sucess");
				arr.add(obj);

			} else {
				result.setSuccess(true);
				result.setMessage("添加错误日志失败 ");

				obj.put("results", "fail");
				arr.add(obj);
			}
		} catch (Exception e) {
			arr.clear();
			logger.error("App报错信息接口异常 ： "+e.getMessage());
		}finally{
			
			writer.println(arr.toString());
			writer.flush();
			writer.close();
		}
	}

	/**
	 * @description 导出数据
	 * @date 2016年8月29日
	 * @author luosf
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/export", method = RequestMethod.GET)
	public void export(AppError appError, HttpServletResponse response) throws Exception {
		try {
			Product product = productService.selectById(Integer.parseInt(appError.getProductId()));
			appError.setProductId(product.getUuid());
			List<AppError> list = appErrorService.findAll(appError);
			String[] header = {"报错类型", "错误信息", "报错时间" ,"手机型号" ,"操作系统" ,"系统版本" ,"APP版本"  };
			String[] colunm = {"functionId", "stacktrace", "errorTime", "phoneModel", "osType", "osVersion", "appVersion" };
			HSSFWorkbook wb = new ExcelUtil<AppError>().export(list, AppError.class, header, colunm, response, "错误数据");
		} catch (Exception e) {
			logger.error("导出APP报错数据异常 : "+e.getMessage());
		}
		
	}

	/**
	 * @description:日登陆次数
	 * @author: luosf
	 * @Time: 2016年9月7日
	 * @return
	 */
	@RequestMapping(value = "/times/day", method = RequestMethod.POST)
	public ModelAndView dayErrorTimesMethod(ErrorAnalysis errorAnalysis) {
		Result<ErrorAnalysis> result = new Result<>();
		try {
			errorAnalysisService.findDayErrorTimes(errorAnalysis);

			result.setObject(errorAnalysis);
			result.setSuccess(true);
			result.setMessage("获取APP错误数据成功");
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage("获取APP错误数据失败");
			logger.error("获取APP错误数据失败 : "+e.getMessage());
		}
		return new ModelAndView(new MappingJackson2JsonView(), "result", result);
	}

	/**
	 * @description:日登陆次数
	 * @author: luosf
	 * @Time: 2016年9月7日
	 * @return
	 */
	@RequestMapping(value = "/times/week", method = RequestMethod.POST)
	public ModelAndView weekErrorTimesMethod(ErrorAnalysis errorAnalysis) {
		Result<ErrorAnalysis> result = new Result<>();
		try {
			errorAnalysisService.findWeekErrorTimes(errorAnalysis);

			result.setObject(errorAnalysis);
			result.setSuccess(true);
			result.setMessage("获取APP错误周数据成功");
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage("获取APP错误周数据失败");
			logger.error("获取APP错误周数据失败 : "+e.getMessage());
		}
		

		return new ModelAndView(new MappingJackson2JsonView(), "result", result);
	}

	/**
	 * @description:日登陆次数
	 * @author: luosf
	 * @Time: 2016年9月7日
	 * @return
	 */
	@RequestMapping(value = "/times/month", method = RequestMethod.POST)
	public ModelAndView monthErrorTimesMethod(ErrorAnalysis errorAnalysis) {
		Result<ErrorAnalysis> result = new Result<>();
		try {
			errorAnalysisService.findMonthErrorTimes(errorAnalysis);

			result.setObject(errorAnalysis);
			result.setSuccess(true);
			result.setMessage("获取APP错误月数据成功");
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage("获取APP错误月数据失败");
			logger.error("获取APP错误月数据失败 : "+e.getMessage());
		}
		return new ModelAndView(new MappingJackson2JsonView(), "result", result);
	}
}
